<template>
  <div class="search">
    <search
      @on-result-click="resultClick"
      @on-change="getResult"
      :results="results"
      v-model="query"
      position="fixed"
      auto-scroll-to-top
      top="0"
      ref="search"
    >
    </search>
    <div class="search-detail" v-if="!!bookDetail.length" v-for="item in bookDetail">
      <img class="search-detail_solt" :src="'http://statics.zhuishushenqi.com'+item.cover">
    </div>
    <tab-bar></tab-bar>
  </div>
</template>
<script>
import { Search } from 'vux';
import TabBar from '@/components/TabBar';
import { getComplete, getFuzzy } from '@/store/api';

function getResult(val) {
  const rs = [];
  for (let i = 0; i < val.length; i += 1) {
    rs.push({
      title: val[i]
    });
  }
  return rs;
}

export default {
  components: {
    TabBar,
    Search
  },
  data() {
    return {
      query: '',
      results: [],
      bookDetail: []
    };
  },
  methods: {
    resultClick(item) {
      getFuzzy({
        query: item.title
      }).then(
        (res) => {
          this.loading = false;
          if (!!res.body.ok) {
            this.query = item.title;
            this.bookDetail = res.body.books;
          } else {
            this.$vux.toast.show({
              text: '获取失败',
              width: '7.6em',
              type: 'text'
            });
          }
        },
        () => {
          this.loading = false;
          this.$vux.toast.show({
            text: '网络错误，请重试',
            type: 'text'
          });
        }
     );
    },
    getResult() {
      getComplete({
        query: this.query
      }).then(
        (res) => {
          this.loading = false;
          if (!!res.body.ok) {
            this.results = getResult(res.body.keywords);
          } else {
            this.$vux.toast.show({
              text: '获取失败',
              width: '7.6em',
              type: 'text'
            });
          }
        },
        () => {
          this.loading = false;
          this.$vux.toast.show({
            text: '网络错误，请重试',
            type: 'text'
          });
        }
     );
    }
  }
};
</script>
<style lang="scss">
  .search {
    .vux-search-box, .weui-search-bar {
      background: #26a2ff;
    }
    .weui-search-bar__cancel-btn {
      color: white;
    }
    .weui-search-bar__label {
      top: 4px;
    }
  }
</style>
